package com.bsh.controller.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.bsh.mybatis.model.Module;
import com.bsh.mybatis.model.Role;
import com.bsh.mybatis.model.RoleModule;
import com.bsh.service.ModuleService;
import com.bsh.service.RoleService;
import com.bsh.utils.PageTools;
import com.google.gson.Gson;
import com.mysql.jdbc.StringUtils;

/**
 * @author gsh
 * @since 0.0.1
 * 
 */
@Controller
public class PermSetController {
	private static Logger log = LoggerFactory.getLogger(PermSetController.class);
	@Autowired
	HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    HttpSession session;    
    @Autowired
    ModuleService moduleService;
	@Autowired
	private RoleService roleService;
	
	
	/**
	 * 角色权限设置 --初使化
	 */
	@RequestMapping(value = "/system/perm/set")
	public ModelAndView permSetInit() {
		List<Role> listRole = roleService.getRoles();
		List<Module> listModule = moduleService.getAllModule();
	
		String selectedRole = request.getParameter("role");	
		if(StringUtils.isNullOrEmpty(selectedRole)){
			Object obj = request.getAttribute("role");
			selectedRole = obj==null?null:obj.toString();
		}
		
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/system/permSet");
		mv.addObject("roleList", listRole);
		mv.addObject("moduleList", listModule);
		mv.addObject("roleId", selectedRole);
		
		if (!StringUtils.isNullOrEmpty(selectedRole)) {
			List<RoleModule> perms = roleService.getRolePermission(Integer.parseInt(selectedRole));
			List<Integer> permsList=new ArrayList<Integer>();
			for (RoleModule roleModule : perms) {
				permsList.add(roleModule.getMoudleId());
			}
			Gson g=new Gson();
			mv.addObject("perms", g.toJson(permsList));
		}
		return mv;
	}

	/**
	 * 保存角色权限 
	 */
	@RequestMapping(value = "/System/perm/save/{roleid}")
	public ModelAndView permSave(@PathVariable(value="roleid") int roleId) {
		ModelAndView mv = new ModelAndView();		
		if(roleId==-1){
			return permSetInit();
		}
		
		String[] moduleList=request.getParameterValues("moduleId");
		roleService.setRoleModules(roleId, moduleList);
		
		request.setAttribute("role",roleId);
		mv= permSetInit();
		mv.addObject("roleId", roleId);		
		
		String msg=PageTools.alert("修改角色权限","保存成功！",1000);
		mv.addObject("actionMsg",msg);
		return mv;
	}
	
	
}
